package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.*;
import org.jsola.hr.dto.excel.EmpChangeImportDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.EmpSocInfoQuery;
import org.jsola.hr.query.EmpSocPlanQuery;
import org.jsola.hr.query.IncreaseDecreaseQuery;
import org.jsola.hr.service.IEmpSocInfoExtraService;
import org.jsola.hr.service.IEmpSocPlanService;
import org.jsola.hr.vo.*;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;


/**
 * 增减员计划表
 *
 * @author zhr
 */
@RestController("hrEmpSocPlanController")
@RequestMapping(HrConstants.API_PATH + "/v1/empSocPlans")
public class EmpSocPlanController implements IEmpSocPlanControllerAPI {

    @Autowired
    private IEmpSocPlanService empSocPlanService;

    @Autowired
    private IEmpSocInfoExtraService empSocInfoExtraService;

    @Override
    @PostMapping
    public Result<EmpSocPlanVO> save(@Valid @RequestBody EmpSocPlanAddDTO empSocPlanAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增增减员计划表权限校验

        return Result.success(
                empSocPlanService.save(empSocPlanAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody EmpSocPlanUpdateDTO empSocPlanUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改增减员计划表权限校验

        int count = empSocPlanService.update(empSocPlanUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{empSocPlanId}")
    public Result<Integer> delete(@PathVariable String empSocPlanId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除增减员计划表权限校验

        int count = empSocPlanService.deleteByIds(tokenUser, empSocPlanId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] empSocPlanIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除增减员计划表权限校验

        int count = empSocPlanService.deleteByIds(tokenUser, empSocPlanIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{empSocPlanId}")
    public Result<EmpSocPlanVO> findById(@PathVariable String empSocPlanId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看增减员计划表权限校验

        return Result.success(
                empSocPlanService.selectById(empSocPlanId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<EmpSocPlanListVO>> listAll(@Valid EmpSocPlanQuery empSocPlanQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看增减员计划表权限校验

        return Result.success(
                empSocPlanService.select(empSocPlanQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<EmpSocPlanListVO>> page(@Valid EmpSocPlanQuery empSocPlanQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocPlanService.selectPage(empSocPlanQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping(value = "/increase")
    public Result<String> increase(@Valid @RequestBody EmpSocPlanBatchAddDTO batchIncreaseDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocPlanService.increase(batchIncreaseDTO, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/decrease")
    public Result<List<CheckDecreaseFailVO>> decrease(@Valid @RequestBody IncreaseDecreaseQuery increaseDecreaseQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocPlanService.decrease(increaseDecreaseQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/increaseOrDecreaseList")
    public Result<Page<EmpSocPlanListVO>> increaseOrDecreaseList(@Valid EmpSocPlanQuery empSocPlanQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocPlanService.increaseOrDecreaseList(empSocPlanQuery, tokenUser)
        );
    }

    @GetMapping(value = "/increaseOrDecreaseListHead")
    public Result<List<KeyNameVO>> increaseOrDecreaseListHead(@Valid EmpSocPlanQuery empSocPlanQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocPlanService.increaseOrDecreaseListHead(empSocPlanQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/increaseDecreaseListCount")
    public Result<EmpSocTransformCountVO> increaseDecreaseListCount(EmpSocPlanQuery empSocPlanQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocPlanService.increaseDecreaseListCount(empSocPlanQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/notFeedbackCount/{companyId}")
    public Result<Integer> notFeedbackCount(@PathVariable String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocPlanService.notFeedbackCount(companyId, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/checkDecrease")
    public Result<List<CheckDecreaseVO>> checkDecrease(@RequestBody List<String> empIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocPlanService.checkDecrease(empIds, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/importIncrease")
    public Result<ImportExcelResultListVO<ImportIncreaseDTO>> importIncrease(@RequestParam("file") MultipartFile file,
                                                                             @RequestParam("companyId") String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                empSocPlanService.importIncrease(excelFile, companyId, tokenUser)
        );
    }

    @Override
    @PostMapping("/exportIncreaseErrorList")
    public ResponseEntity<Resource> exportIncreaseErrorList(@Valid @RequestBody ImportExcelResultListVO<ImportIncreaseDTO> errorList) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工参保信息表权限校验
        String excelFilePath = empSocPlanService.exportIncreaseErrorList(errorList);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @PostMapping(value = "/importDecrease")
    public Result<ImportExcelResultListVO<ImportDecreaseDTO>> importDecrease(@RequestParam("file") MultipartFile file,
                                                                             @RequestParam("companyId") String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                empSocPlanService.importDecrease(excelFile, companyId, tokenUser)
        );
    }

    @Override
    @PostMapping("/exportDecreaseErrorList")
    public ResponseEntity<Resource> exportDecreaseErrorList(@Valid @RequestBody ImportExcelResultListVO<ImportDecreaseDTO> errorInfo) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工参保信息表权限校验
        String excelFilePath = empSocPlanService.exportDecreaseErrorList(errorInfo);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @GetMapping(value = "/confirmSocBySite")
    public Result<String> confirmSocBySite() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 临时保存到本地
        return Result.success(
                empSocInfoExtraService.getConfirmSocBySite(tokenUser)
        );
    }

    @Override
    @PutMapping(value = "/cancelDecrease/{planId}")
    public Result<String> cancelDecrease(@PathVariable String planId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 临时保存到本地
        empSocInfoExtraService.cancelDecrease(planId, tokenUser);
        return Result.success(

        );
    }

    @Override
    @PutMapping(value = "/cancelIncrement/{planId}")
    public Result<String> cancelIncrement(@PathVariable String planId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 临时保存到本地
        empSocInfoExtraService.cancelIncrement(planId, tokenUser);
        return Result.success(

        );
    }

    @Override
    @PostMapping(value = "/increaseExtra")
    public Result<String> increaseExtra(@RequestBody EmpSocPlanBatchAddDTO batchIncreaseDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        String confirmSocBySite = empSocInfoExtraService.getConfirmSocBySite(tokenUser);
        String result;
        if ("是".equals(confirmSocBySite)) {
            result = empSocInfoExtraService.increaseExtra(batchIncreaseDTO, tokenUser);
        } else {
            result = empSocPlanService.increase(batchIncreaseDTO, tokenUser);
        }
        return Result.success(result);
    }

    @Override
    @PutMapping(value = "/increaseUpdateExtra")
    public Result<String> increaseUpdateExtra(@RequestBody IncreaseDecreaseUpdateDTO increaseUpdate) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        empSocInfoExtraService.increaseUpdateExtra(increaseUpdate, tokenUser);
        return Result.success();
    }

    @Override
    @PutMapping(value = "/increaseFeedbackExtra")
    public Result<String> increaseFeedbackExtra(@RequestBody EmpSocPlanAttachDTO empSocPlanAttachDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        empSocInfoExtraService.increaseFeedbackExtra(empSocPlanAttachDTO, tokenUser);
        return Result.success();
    }

    @Override
    @PostMapping(value = "/decreaseExtra")
    public Result<List<CheckDecreaseFailVO>> decreaseExtra(@RequestBody IncreaseDecreaseQuery decreaseQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验
        String confirmSocBySite = empSocInfoExtraService.getConfirmSocBySite(tokenUser);
        List<CheckDecreaseFailVO> result;
        if ("是".equals(confirmSocBySite)) {
            result = empSocInfoExtraService.decreaseExtra(decreaseQuery, tokenUser);
        } else {
            result = empSocPlanService.decrease(decreaseQuery, tokenUser);
        }
        return Result.success(result);
    }

    @Override
    @PutMapping(value = "/decreaseUpdateExtra")
    public Result<String> decreaseUpdateExtra(@RequestBody IncreaseDecreaseUpdateDTO decreaseUpdate) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        empSocInfoExtraService.decreaseUpdateExtra(decreaseUpdate, tokenUser);
        return Result.success();
    }

    @Override
    @PutMapping(value = "/decreaseFeedbackExtra")
    public Result<String> decreaseFeedbackExtra(@RequestBody EmpSocPlanAttachDTO empSocPlanAttachDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        empSocInfoExtraService.decreaseFeedbackExtra(empSocPlanAttachDTO, tokenUser);
        return Result.success();
    }

    @GetMapping(value = "/jfEmpSocInfo/{empId}")
    public Result<JfEmpSocInfoVO> jfEmpSocInfo(@PathVariable String empId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoExtraService.jfEmpSocInfo(empId, tokenUser)
        );
    }

    @GetMapping(value = "/jfEmpSocInfoList")
    public Result<Page<EmpSocInfoListVO>> jfEmpSocInfoList(@Valid EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoExtraService.jfEmpSocInfoList(empSocInfoQuery, tokenUser)
        );
    }

    @GetMapping(value = "/jfStatisticsAnalyseSoc")
    public Result<JfStatisticsAnalyseVO> jfStatisticsAnalyseSoc(@Valid EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoExtraService.jfStatisticsAnalyseSoc(empSocInfoQuery, tokenUser)
        );
    }

}

